/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.odg.dg.impl;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.opu.odg.dg.incomingdata.DatabaseSettings;

/**
 *
 * @author yura
 */
public class ConnectionHolder {

    private Map<DatabaseSettings, Connection> connections
            = new HashMap<DatabaseSettings, Connection>();

    private DatabaseSettings defaultDatabaseSettings;

    public ConnectionHolder(DatabaseSettings defaultDatabaseSettings,
            Connection defaultConnection) {
        this(defaultDatabaseSettings);
        connections.put(defaultDatabaseSettings, defaultConnection);
    }

    public ConnectionHolder(DatabaseSettings defaultDatabaseSettings) {
        this.defaultDatabaseSettings = defaultDatabaseSettings;
    }

    public Connection getConnection(DatabaseSettings databaseSettings) {
        if (databaseSettings == null) {
            if (defaultDatabaseSettings != null) {
                return getConnection(defaultDatabaseSettings);
            } else {
                throw new NullPointerException("Default database settings is not defined.");
            }
        }

        Connection connection = connections.get(databaseSettings);
        if (connection == null) {
            try {
                Class.forName(databaseSettings.getDriver()).newInstance();
            } catch (Exception ex) {
                throw new IllegalArgumentException(ex);
            }

            try {
                if (StringUtils.isEmpty(databaseSettings.getUser())
                        && StringUtils.isEmpty(databaseSettings.getPswd())) {
                    connection = DriverManager.getConnection(databaseSettings.getUrl());
                } else {
                    connection = DriverManager.getConnection(
                            databaseSettings.getUrl(),
                            databaseSettings.getUser(),
                            databaseSettings.getPswd());
                }
            } catch (SQLException ex) {
                throw new IllegalArgumentException(ex);
            }

            connections.put(databaseSettings, connection);
        }

        return connection;
    }

    public DatabaseSettings getDefaultDatabaseSettings() {
        return defaultDatabaseSettings;
    }

    public void setDefaultDatabaseSettings(DatabaseSettings defaultDatabaseSettings) {
        this.defaultDatabaseSettings = defaultDatabaseSettings;
    }

    void close() throws IOException {
        Exception exception = null;
        for (Map.Entry<DatabaseSettings, Connection> entry : connections.entrySet()) {
            if (!defaultDatabaseSettings.equals(entry.getKey())) {
                try {
                    entry.getValue().close();
                } catch (Exception ex) {
                    exception = ex;
                }
            }
        }

        if (exception != null) {
            throw new IOException(exception);
        }
    }
}
